package th.retrofit.lib;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/combinations/
 */
final class Solution77 {

    /**
     * 1 <= n <= 20
     * 1 <= k <= n
     * @param n 给定整数 n
     * @param k 给定整数k
     * @return 返回范围 [1, n] 中所有可能的 k 个数的组合
     */
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> combine = new ArrayList<>(k);
        dfs(results, combine, n, k, 1);
        return results;
    }

    private void dfs(List<List<Integer>> results, List<Integer> combine,
                     int n, int k, int begin) {
        if (combine.size() == k) {
            results.add(new ArrayList<>(combine));
            return;
        }
        for (int i = begin; i <= n; i++) {
            combine.add(i);
            dfs(results, combine, n, k, i + 1);
            combine.remove(combine.size() - 1);
        }
    }

    /**
     * 1 <= n <= 20
     * 1 <= k <= n
     * @param n 给定整数 n
     * @param k 给定整数k
     * @return 返回范围 [1, n] 中所有可能的 k 个数的组合
     */
    public List<List<Integer>> combine1(int n, int k) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> combine = new ArrayList<>(k);
        backstack(results, combine, n, k, 1);
        return results;
    }

    private void backstack(List<List<Integer>> results, List<Integer> combine,
                     int n, int k, int index) {
        if (combine.size() + n - index  + 1 < k) {
            return;
        }
        if (combine.size() == k) {
            results.add(new ArrayList<>(combine));
            return;
        }
        backstack(results, combine, n, k, index + 1);
        combine.add(index);
        backstack(results, combine, n, k, index + 1);
        combine.remove(combine.size() - 1);
    }

    public static void main(String[] args) {
        new Solution77().combine1(4, 2).forEach(it -> {
            it.forEach(System.out::print);
            System.out.println();
        });
    }

}
